<?php
/**
 * Create DataConvert.php by Jurij.cao
 * Notes:数据转化(格式化)
 * Date:2022/6/23
 */

namespace App\Common;

class DataConvert
{
    use Singleton;

    /**
     * Notes:加密数据
     * @param $value
     * @return string
     */
    public static function encode($value): string
    {
        switch (true) {
            case is_array($value) :
                $data = [
                    'value_type' => 'array',
                    'value' => json_encode($value,JSON_UNESCAPED_UNICODE)
                ];
                break;
            case is_object($value) :
                $data = [
                    'value_type' => 'object',
                    'value' => json_encode($value)
                ];
                break;
            default :
                $data = [
                    'value_type' => 'default',
                    'value' => $value
                ];
        }

        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    /**
     * Notes:解密数据
     * @param mixed $data
     * @return mixed
     */
    public static function decode(string $data)
    {
        $data = json_decode($data,true);
        switch ($data['value_type']) {
            case 'array':
                $result = json_decode($data['value'], true);
                break;
            case 'object':
                $result = json_decode($data['value']);
                break;
            default:
                $result = $data['value'];
                break;
        }
        return $result;
    }
}

